package com.bing.dao.impl;

import com.bing.dao.PostDao;
import com.bing.entity.Post;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by kaibb on 15-11-28.
 */

@Repository
public class PostDaoImpl extends BaseDaoImpl<Post, Long> implements PostDao {

    public static final String GET_PRE = "Select distinct Post_id from Post_tags where Post_id<:Post_id tags in (:tags) order by Post_id desc";
    public static final String GET_NEXT = "Select distinct Post_id from Post_tags where Post_id>:Post_id tags in (:tags) order by Post_id asc";

    @Override
    public List<String> getTags() {
        SQLQuery namedQuery = getSession().createSQLQuery("select DISTINCT (tags) FROM Post_tags");
        return namedQuery.list();
    }

    @Override
    public Post getPre(Long id, List<String> tags) {
        return getPost(GET_PRE,id, tags);
    }

    public Post getPost(String sql,Long id, List<String> tags) {
        SQLQuery sqlQuery = getSession().createSQLQuery(sql);
        sqlQuery.setParameter("Post_id", id);
        sqlQuery.setParameterList("tags", tags);
        sqlQuery.setMaxResults(1);
        List list = sqlQuery.list();
        if (list.size() == 1) {
            return findById((Long) list.get(0));
        }
        return null;
    }

    @Override
    public Post getNext(Long id,List<String> tags) {
        return getPost(GET_NEXT,id,tags);
    }
}
